﻿#include "sapmsginterface.h"
//sapMsgInterface* sapMsgInterface::instance=nullptr;
//QMutex sapMsgInterface::mutex;

STATEMENTINSTANCE(sapMsgInterface)
#define ASMORDERDBSTR ConnectPoolFactory::getInstance()->getConnectPool(ConnectPoolFactory::AsmOrderDataBase0)

sapMsgInterface::sapMsgInterface(QObject *parent) : QObject(parent)
{
    setSapPathMap();
    //ws01Path="http://algnts30.algex.asmpt.com/SpecialStorageWS/OKAGVWarehouseWS.svc/REST/Details?label=";
    //ws01Path="http://10.16.209.76/Service.svc/Details?label=";

    qRegisterMetaType<QList<labelMsgStruct >>("QList<labelMsgStruct >");
    qRegisterMetaType<QList<retMsgStruct >>("QList<retMsgStruct >");
    qRegisterMetaType<QMap<int,sapPath>>("QMap<int,sapPath>");

    connect(&NetworkMgr, SIGNAL(finished(QNetworkReply *)),SLOT(ReadResponse(QNetworkReply *)));

    connect(this,&sapMsgInterface::ReplyError,this,&sapMsgInterface::ONReplyError);

    MsgTimer = new QTimer(this);
    connect(MsgTimer,&QTimer::timeout,this,&sapMsgInterface::sapMsgTimer);
    MsgTimer->start(300);

}

void sapMsgInterface::sapMsgTimer()
{
    if(WebServiceItiemMap.isEmpty() && !WebServiceMap.isEmpty()){
        WebService WebServiceI= WebServiceMap.first();
        setWebService_Get(WebServiceI.LabelNo,sapPathMap.value(WebServiceI.pathId).Path+WebServiceI.LabelNo,
                          WebServiceI.UserBadge,sapPathMap.value(WebServiceI.pathId).Type);
        WebServiceMap.remove(WebServiceI.LabelNo);
        qDebug()<<"WS01 LabelNo 0:"<<WebServiceI.LabelNo<<"  size: "<<WebServiceMap.size()<<WebServiceItiemMap.size();
    }

}

//SAP 返回数据
void sapMsgInterface::ReadResponse(QNetworkReply *Reply)
{
    switch (Reply->error()) {
        case QNetworkReply::NoError:
        case QNetworkReply::ContentAccessDenied://数据库拒绝访问
        case QNetworkReply::ContentOperationNotPermittedError://内容操作批准未通过
        case QNetworkReply::ContentNotFoundError://内容没有找到
        case QNetworkReply::UnknownContentError:
        {
            QByteArray ReplyData;
            ReplyData=Reply->readAll();
            //qDebug()<<"ReplyData: "<<ReplyData;

            QJsonDocument JsonAnalyse; QJsonParseError JsonError;
            QJsonArray Jsonarray;
            JsonAnalyse = QJsonDocument::fromJson(ReplyData,&JsonError);

            if(JsonError.error == QJsonParseError::NoError)
            {
                if(!(JsonAnalyse.isEmpty() || JsonAnalyse.isNull()))
                {
                    for(int i=0;i<WebServiceItiemMap.length();i++){
                        if(WebServiceItiemMap[i].NetworkRepItiem==Reply){


                            qDebug()<<"MES 返回数据--->actionType:"<<WebServiceItiemMap[i].actionType<<WebServiceItiemMap[i].ikey<<"\n"
                                      <<"JsonAnalyse:"<<JsonAnalyse;

                            analysReplyJson(WebServiceItiemMap[i].ikey,JsonAnalyse,WebServiceItiemMap[i].actionType,WebServiceItiemMap[i].positionCode);
                            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
                            WebServiceItiemMap.removeAt(i);
                            i--;
                        }

                    }
                }
            }
        }
            break;
        default:
        {
            // HTTP错误代码解析: https://blog.csdn.net/qq_32963841/article/details/78365449
            int HttpStatus = Reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();//错误代码
            QString Errorinfo="error http Status: "+QString::number(HttpStatus);
            QString Errorinfo1=(QString("Network transport error (%1): %2").arg(Reply->error()).arg(Reply->errorString()));//系统信息

            QJsonObject ReplyJson ;
            QJsonDocument JsonAnalyse; QJsonParseError JsonError;
            for(int i=0;i<WebServiceItiemMap.length();i++){
                if(WebServiceItiemMap[i].NetworkRepItiem==Reply){
                    QByteArray ReplyData;
                    ReplyData=Reply->readAll();
                    JsonAnalyse = QJsonDocument::fromJson(ReplyData,&JsonError);
                    //qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd_hh:mm:ss")<<"ikey:"<<WebServiceItiemMap[i].ikey<<"size:"<<WebServiceItiemMap.size();
                    qDebug()<<"Errorinfo:"<<Errorinfo<<Errorinfo1<<Reply->error();

                    ReplyJson.insert("result","E1");
                    ReplyJson.insert("message","请求超时");
                    analysReplyJson(WebServiceItiemMap[i].ikey,JsonAnalyse,WebServiceItiemMap[i].actionType,"");
//                    WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
//                    WebServiceItiemMap.removeAt(i);i--;

                    emit ReplyError(WebServiceItiemMap[i]);//因网络异常 重发 三次机制
                }
            }

        }
        break;
    }
}

void sapMsgInterface::ONReplyError(WebServiceItiem WebServiceItiemI)
{
    int count=1;
    if(currentIkeyMap.contains(WebServiceItiemI.ikey)){
        qDebug()<<"重发结束 ONReplyError e: "<<WebServiceItiemI.ikey<<WebServiceItiemI.actionType<<"第几次: "<<count;
        return;
    }
    if(!currentIkeyMap.contains(WebServiceItiemI.ikey)){
        currentIkeyMap.insert(WebServiceItiemI.ikey,count);
    }
    qDebug()<<"ONReplyError: "<<WebServiceItiemI.ikey<<WebServiceItiemI.actionType<<"第几次: "<<count;
    QJsonObject ReplyJson;
    ReplyJson_Msg_ESS(WebServiceItiemI.ikey,ReplyJson,WebServiceItiemI.actionType,"");

}


//SAP 反馈数据解析
void sapMsgInterface::analysReplyJson(QString iKey, QJsonDocument JsonAnalyse, QString actionType,QString positionCode)
{
    QJsonObject ReplyJson = JsonAnalyse.object();//取得最外层这个大对象
    ReplyJson_Msg_ESS(iKey,ReplyJson,actionType,positionCode);
}

void sapMsgInterface::setSapPathMap()
{
    QVariant valuemin;
    if(setting::getInstance()->getSettingValueInterface("ASMOrderDB/sapPath", valuemin))
    {
        currentsapPath = valuemin.toInt();
    }
    //currentsapPath=30;
    connectBuilder build(ASMORDERDBSTR);
    QSqlDatabase sqlDatabase =  build.getOpenDatabase();

    QSqlQuery sqlQuery(sqlDatabase);
    sqlQuery.setForwardOnly(true);

    sqlQuery.prepare("select * from sapPath;");

    if(sqlQuery.exec())
    {
        while(sqlQuery.next())
        {
            sapPath sapPathI;
            sapPathI.Id=sqlQuery.value("Id").toInt();
            sapPathI.Path=sqlQuery.value("Path").toString();
            sapPathI.funcation=sqlQuery.value("funcation").toString();
            sapPathI.para1=sqlQuery.value("para1").toString();
            sapPathI.para2=sqlQuery.value("para2").toString();
            sapPathI.para3=sqlQuery.value("para3").toString();

            if(sapPathI.funcation!="" && sapPathI.Id<100){
                QString path=sapPathI.funcation+"?";
                if(sapPathI.para1!=""){
                     path=path+sapPathI.para1+"=";
                    if(sapPathI.para2!=""){
                         path="&"+path+sapPathI.para2+"=";
                        if(sapPathI.para3!=""){
                             path="&"+path+sapPathI.para3+"=";
                        }
                    }
                }
                sapPathI.Path=sapPathI.Path+path;
            }

            //qDebug()<<sapPathI.Id<<sapPathI.Path;

            sapPathI.Type=sqlQuery.value("Type").toString();        //路径类型 发料时根据类型 选择路径
            sapPathI.PathName=sqlQuery.value("PathName").toString();
            sapPathMap.insert(sapPathI.Id,sapPathI);
        }
    }

}

QMap<int ,sapPath > sapMsgInterface::getsapPathMap()
{
    return sapPathMap;
}

void sapMsgInterface::setLabelMsgclear()
{
    WebServiceMap.clear();
}



//<<<<<<<<<<WS01<<<<<<<<<<<<  lABELNo:时间戳
void sapMsgInterface::getLabelMsg(QString LabelNo, QString UserBadge,int pathId,int station)
{
    WebService WebServiceI;
    WebServiceI.LabelNo=LabelNo;
    WebServiceI.UserBadge=UserBadge;
    WebServiceI.pathId=pathId;
    if(WebServiceItiemMap.size()<WebConut){
        setWebService_Get(LabelNo,sapPathMap.value(pathId).Path+QString::number(station),UserBadge,sapPathMap.value(pathId).Type);
        return;
    }
    if(!WebServiceMap.contains(LabelNo)){
        WebServiceMap.insert(WebServiceI.LabelNo,WebServiceI);
    }

}

//<<<<<<<<<<WS01 Reply<<<<<<<<<<<<
void sapMsgInterface::ReplyJson_Msg_MES(QString iKey, QJsonObject ReplyJson,QString actionType)
{
    ReplyMsg ReplyMsgI;
    ReplyMsgI.keyId=iKey;
    if(!ReplyJson.isEmpty()){
        ReplyMsgI.status=ReplyJson.value("retcode").toInt();
        ReplyMsgI.errorMsg=ReplyJson.value("message").toString();
    }else{
        ReplyMsgI.status=-1;
        ReplyMsgI.errorMsg="提交失败";
    }
    ReplyMsgI.ReplyJson=ReplyJson;

    ReplyMsgMap.insert(iKey,ReplyMsgI);
    qDebug()<<"<<<<< set ReplyJson_Msg_MES <<<<< iKey:"<<iKey<<" status:"<<ReplyMsgI.status<<" errorMsg:"<<ReplyMsgI.errorMsg<<" Json:"<<ReplyMsgI.ReplyJson;

}

void sapMsgInterface::ReplyJson_Msg_ESS(QString iKey, QJsonObject ReplyJson,QString actionType,QString positionCode)
{
    ReplyMsg ReplyMsgI;
    ReplyMsgI.keyId=iKey;
    if(!ReplyJson.isEmpty()){
        ReplyMsgI.status=ReplyJson.value("retcode").toInt();
        ReplyMsgI.errorMsg=ReplyJson.value("message").toString();
        ReplyMsgI.ReplyJson=ReplyJson;
    }else{
        ReplyMsgI.status=-1;
        ReplyMsgI.errorMsg="提交失败";
    }
    ReplyMsgMap.insert(iKey,ReplyMsgI);
    qDebug()<<"<<<<< set ReplyJson_Msg_ESS <<<<< iKey:"<<iKey<<" status:"<<ReplyMsgI.status<<" errorMsg:"<<ReplyMsgI.errorMsg<<" Json:"<<ReplyMsgI.ReplyJson;
}

ReplyMsg sapMsgInterface::GetMsgRecv_Msg(QString iKey)
{
    ReplyMsg ReplyMsgI;
    if(ReplyMsgMap.contains(iKey)){
        ReplyMsgI=ReplyMsgMap.value(iKey);
        ReplyMsgMap.remove(iKey);
        qDebug()<<"<<<<< get GetMsgRecv_Mes <<<<< keyId:"<<iKey<<" status:" <<ReplyMsgI.status<<" errorMsg:"<<ReplyMsgI.errorMsg<<ReplyMsgI.datalist.size();
    }
    return ReplyMsgI;
}


void sapMsgInterface::taskCodes_MES(QString iKey, ESS_Request ESS_RequestI, QString UserBadge, int pathId)
{
    //qDebug()<<iKey<<WWYLPOSTII.actionId<<UserBadge<<pathId;
    QJsonObject postJson=posttaskCodes_MES(iKey,ESS_RequestI);
    setWebService_Post(iKey,sapPathMap.value(pathId).Path,postJson,UserBadge,sapPathMap.value(pathId).Type,"");
}

QJsonObject sapMsgInterface::posttaskCodes_MES(QString iKey, ESS_Request ESS_RequestI)
{
    //0查询状态  1任务查询  2出库  3移库  4回库  5任务取消
    QJsonObject tasksJson;
    /*******下达订单任务************/
    if(ESS_RequestI.actionId=="WS01"){
        tasksJson.insert("taskId",ESS_RequestI.taskId);                 //订单编码唯一
        tasksJson.insert("taskType",ESS_RequestI.taskType);             //任务类型
        tasksJson.insert("agvId",ESS_RequestI.agvId);                   //配送小车编号
        tasksJson.insert("priority",ESS_RequestI.priority);             //任务优先级
        tasksJson.insert("load",ESS_RequestI.load);                     //装机站点
        tasksJson.insert("workStation",ESS_RequestI.workStation);       //老化工位
        tasksJson.insert("unload",ESS_RequestI.unload);                 //下机站点
        tasksJson.insert("finishNode",ESS_RequestI.finishNode);         //完成返回站点 等待点.

    }

    /*******返回任务状态************/
    if(ESS_RequestI.actionId=="WS02"){
        tasksJson.insert("taskId",ESS_RequestI.taskId);                 //订单编码唯一
        tasksJson.insert("status",ESS_RequestI.status);
        tasksJson.insert("message",ESS_RequestI.message);

    }
    //qDebug()<<iKey<<ReJson;
    return  tasksJson;
}


 /***ESS_P协议: 0查询状态  1任务查询  2出库  3移库  4回库  5任务取消***/
void sapMsgInterface::robotCodes_query(QString iKey, ESS_Request ESS_RequestI,QString UserBadge,int pathId)
{
    QJsonObject postJson=postrobotCodes_query(iKey,ESS_RequestI);
    setWebService_Post(iKey,sapPathMap.value(pathId).Path,postJson,UserBadge,sapPathMap.value(pathId).Type,"");
}

void sapMsgInterface::robotCodes_query_Get(QString iKey, ESS_Request ESS_RequestI, QString UserBadge, int pathId)
{
    setWebService_Get(iKey,sapPathMap.value(pathId).Path+ESS_RequestI.robotCode,UserBadge,sapPathMap.value(pathId).Type);
}

QJsonObject sapMsgInterface::postrobotCodes_query(QString iKey, ESS_Request ESS_RequestI)
{
    QJsonObject rootObj;
    QJsonArray rootFruitList;
    for(int i = 0;i<ESS_RequestI.robotCodes.size();i++){
        rootFruitList.append(ESS_RequestI.robotCodes.at(i));
    }
    rootObj.insert("robotCodes", rootFruitList);
    return  rootObj;
}

void sapMsgInterface::taskCodes_query(QString iKey, ESS_Request ESS_RequestI,QString UserBadge,int pathId)
{
    QJsonObject postJson=posttaskCodes_query(iKey,ESS_RequestI);
    setWebService_Post(iKey,sapPathMap.value(pathId).Path,postJson,UserBadge,sapPathMap.value(pathId).Type,"");
}

QJsonObject sapMsgInterface::posttaskCodes_query(QString iKey, ESS_Request ESS_RequestI)
{
    QJsonObject rootObj;
    QJsonArray rootFruitList;
    for(int i = 0;i<ESS_RequestI.taskCodes.size();i++){
        rootFruitList.append(ESS_RequestI.taskCodes.at(i));
    }
    rootObj.insert("taskCodes", rootFruitList);
    return  rootObj;
}

//向查询相机库位状态
void sapMsgInterface::cameraCodes_query_Get(QString iKey,int stationId,int pathId)
{

    WebService WebServiceI;
    WebServiceI.pathId=pathId;
    WebServiceI.stationId = stationId;  //摄像头查询ID
    if(WebServiceItiemMap.size()<WebConut){
        setWebService_Get_Camera(iKey,sapPathMap.value(pathId).Path+QString::number(stationId),sapPathMap.value(pathId).Type);
        return;
    }

}

void sapMsgInterface::taskCodes_actionId(QString iKey, ESS_Request ESS_RequestI, QString UserBadge,int pathId,QString Type)
{
    qDebug()<<"taskCodes_actionId:"<<iKey<<ESS_RequestI.actionId<<UserBadge<<pathId;
    QJsonObject postJson;
    postJson=posttaskCodes_actionId(Type,ESS_RequestI);
    setWebService_Post(iKey,sapPathMap.value(pathId).Path,postJson,UserBadge,sapPathMap.value(pathId).Type,"");

}

QJsonObject sapMsgInterface::posttaskCodes_actionId(QString Type, ESS_Request ESS_RequestI)
{
    QJsonObject tasksJson;
    /********** 任务指令 ************/
    if(Type=="agvTask" || Type=="agvMove"){
         tasksJson.insert("taskId",ESS_RequestI.ESS_AGV0.taskId);                       //订单编码唯一
         tasksJson.insert("taskType",ESS_RequestI.ESS_AGV0.taskType);                   //任务类型  1入料 2出料 3呼叫空架
         tasksJson.insert("agvId",ESS_RequestI.ESS_AGV0.agvId);                         //AGV编号
         tasksJson.insert("priority",ESS_RequestI.ESS_AGV0.priority);                   //优先级
         tasksJson.insert("finishNode",ESS_RequestI.ESS_AGV0.finishNode);               //完成返回点

         tasksJson.insert("load",ESS_RequestI.ESS_AGV0.load);                           //装机站点
         tasksJson.insert("loadWaitNode",ESS_RequestI.ESS_AGV0.loadWaitNode);           //装机站点 等待点
         tasksJson.insert("loadAnglePose",ESS_RequestI.ESS_AGV0.loadAnglePose);         //姿态角度
         tasksJson.insert("loadAngleRotary",ESS_RequestI.ESS_AGV0.loadAngleRotary);     //顶盘角度

         tasksJson.insert("unload",ESS_RequestI.ESS_AGV0.unload);                       //装机站点
         tasksJson.insert("unloadWaitNode",ESS_RequestI.ESS_AGV0.unloadWaitNode);       //装机站点 等待点
         tasksJson.insert("unloadAnglePose",ESS_RequestI.ESS_AGV0.unloadAnglePose);     //姿态角度
         tasksJson.insert("unloadAngleRotary",ESS_RequestI.ESS_AGV0.unloadAngleRotary); //顶盘角度

         tasksJson.insert("workStation",ESS_RequestI.ESS_AGV0.workStation);             //装机站点
         tasksJson.insert("workWaitStation",ESS_RequestI.ESS_AGV0.workWaitStation);     //装机站点 等待点
         tasksJson.insert("workAnglePose",ESS_RequestI.ESS_AGV0.workAnglePose);         //姿态角度
         tasksJson.insert("workAngleRotary",ESS_RequestI.ESS_AGV0.workAngleRotary);     //顶盘角度

         tasksJson.insert("work2Station",ESS_RequestI.ESS_AGV0.work2Station);           //装机站点
         tasksJson.insert("work2WaitStation",ESS_RequestI.ESS_AGV0.work2WaitStation);   //装机站点 等待点
         tasksJson.insert("work2AnglePose",ESS_RequestI.ESS_AGV0.work2AnglePose);       //姿态角度
         tasksJson.insert("work2AngleRotary",ESS_RequestI.ESS_AGV0.work2AngleRotary);   //顶盘角度

    }if(Type=="agvRun"){
        tasksJson.insert("taskId",ESS_RequestI.taskId);
        tasksJson.insert("status",ESS_RequestI.status);
        tasksJson.insert("WaitStation",ESS_RequestI.WaitStation);
    }/*if(Type=="agvMove"){
        tasksJson.insert("taskId",ESS_RequestI.ESS_AGV0.taskId);                       //订单编码唯一
        tasksJson.insert("taskType",ESS_RequestI.ESS_AGV0.taskType);                   //任务类型  1入料 2出料 3呼叫空架
        tasksJson.insert("agvId",ESS_RequestI.ESS_AGV0.agvId);                         //AGV编号
        tasksJson.insert("priority",ESS_RequestI.ESS_AGV0.priority);                   //优先级
        tasksJson.insert("finishNode",ESS_RequestI.ESS_AGV0.finishNode);               //完成返回点
   }*/

    qDebug()<<"posttaskCodes_actionId -->taskType:"<<ESS_RequestI.ESS_AGV0.taskType<<" tasksJson:"<<tasksJson;
    return  tasksJson;
}


void sapMsgInterface::taskCodes_cancel(QString iKey, ESS_Request ESS_RequestI,QString UserBadge,int pathId)
{
    qDebug()<<"taskCodes_cancel:"<<iKey<<ESS_RequestI.actionId;
    QJsonObject postJson=posttaskCodes_cancel(iKey,ESS_RequestI);
    setWebService_Post(iKey,sapPathMap.value(pathId).Path,postJson,UserBadge,sapPathMap.value(pathId).Type,"");
}

QJsonObject sapMsgInterface::posttaskCodes_cancel(QString iKey, ESS_Request ESS_RequestI)
{
    QJsonObject rootObj;
    QJsonArray rootFruitList;
    for(int i = 0;i<ESS_RequestI.taskCodes.size();i++){
        rootFruitList.append(ESS_RequestI.taskCodes.at(i));
    }
    rootObj.insert("taskCodes", rootFruitList);
    return  rootObj;
}

QJsonObject sapMsgInterface::JsonTaskAgvMove(SAPExcelInfo SAPExcelInfoI, int station, QString taskType, int moveFlag, bool flag)
{
    QJsonObject taskjson;
    QJsonObject taskjson1;
    QJsonObject taskjson2;
    QJsonArray taskjosnList;
    QJsonArray List;

    if(flag)
    {
        taskjson2.insert("unitId", SAPExcelInfoI.taskId_ess + "-Start");//子任务 ID
        taskjson2.insert("taskType", 3);                                //任务类型
        taskjson2.insert("station", 0);                                 //目标站点
        taskjson2.insert("actionSource", 251);                          //执行动作源标记
        taskjson2.insert("actionCode", 3);                              //动作命令
        taskjson2.insert("moveFlag", moveFlag);                         //顶盘状态 0：保持 1：降下移动 2：举升移动

        List.insert(0, 4);
        List.insert(1, 0);
        List.insert(2, 0);
        List.insert(3, 0);
        List.insert(4, 0);
        List.insert(5, 0);
        List.insert(6, 0);
        List.insert(7, 0);

        taskjson2.insert("paraList", List);                             //动作参数列表

        taskjosnList.append(taskjson2);                                 //任务列表
    }

    taskjson.insert("taskId", SAPExcelInfoI.taskId);                    //任务 ID
    taskjson.insert("agvId", SAPExcelInfoI.agvNum.toInt());             //AGV编号

    taskjson1.insert("unitId", SAPExcelInfoI.taskId_ess);               //子任务 ID
    taskjson1.insert("taskType", 1);                                    //任务类型
    taskjson1.insert("station", station);                               //目标站点

    if(taskType == "MOVE"){
        taskjson1.insert("endConfirm", 1);                              //任务完成后确认 一般用于放行 0:不启用 1:启用
    }

    taskjson1.insert("agvAngle", 0);                                    //小车角度
//    taskjson1.insert("moveFlag", moveFlag);                             //顶盘状态 0：保持 1：降下移动 2：举升移动

    taskjosnList.append(taskjson1);                                     //任务列表

    taskjson.insert("taskList", taskjosnList);                          //任务列表

    return  taskjson;
}

void sapMsgInterface::PostTaskAgvMove(SAPExcelInfo SAPExcelInfoI, int station, QString taskType, int moveFlag, bool flag)
{
    qDebug()<<"PostTaskAgvMove-->"<<" taskId:"<<SAPExcelInfoI.taskId<<" taskId_ess:"<<SAPExcelInfoI.taskId_ess
           <<" agvNum:"<<SAPExcelInfoI.agvNum<<" station:"<<station<<" taskType:"<<taskType<<" moveFlag:"<<moveFlag<<" flag:"<<flag;
    QJsonObject postJson = JsonTaskAgvMove(SAPExcelInfoI, station, taskType, moveFlag, flag);
    setWebService_Post(SAPExcelInfoI.taskId_ess, sapPathMap.value(1014).Path, postJson, "", sapPathMap.value(1014).Type, "");
}

QJsonObject sapMsgInterface::JsonTaskAgvAction(SAPExcelInfo SAPExcelInfoI, int station, int actionCode, QString taskType, int moveFlag, bool flag)
{
    QJsonObject taskjson;
    QJsonObject taskjson1;
    QJsonObject taskjson2;
    QJsonArray taskjosnList;
    QJsonArray List;
    QJsonArray List1;

    taskjson.insert("taskId", SAPExcelInfoI.taskId);                    //任务 ID
    taskjson.insert("agvId", SAPExcelInfoI.agvNum.toInt());             //AGV编号

    if(flag)
    {
        taskjson2.insert("unitId", SAPExcelInfoI.taskId_ess + "-Start");//子任务 ID
        taskjson2.insert("taskType", 3);                                //任务类型
        taskjson2.insert("station", 0);                                 //目标站点
        taskjson2.insert("actionSource", 251);                          //执行动作源标记  0：自定义动作，251：内部动作，252：外部动作
        taskjson2.insert("actionCode", 3);                              //动作命令 4：顶盘举升 3：顶盘下降
        taskjson2.insert("moveFlag", moveFlag);                         //顶盘状态 0：保持 1：降下移动 2：举升移动

        List1.insert(0, 4);
        List1.insert(1, 0);
        List1.insert(2, 0);
        List1.insert(3, 0);
        List1.insert(4, 0);
        List1.insert(5, 0);
        List1.insert(6, 0);
        List1.insert(7, 0);

        taskjson2.insert("paraList", List1);                             //动作参数列表

        taskjosnList.append(taskjson2);                                 //任务列表
    }

    taskjson1.insert("unitId", SAPExcelInfoI.taskId_ess);               //子任务 ID
    taskjson1.insert("taskType", 3);                                    //任务类型
    taskjson1.insert("station", station);                               //目标站点

    if(taskType == "Action")
    {
        taskjson1.insert("endConfirm", 1);                              //任务完成后确认，一般用于放行
    }

    taskjson1.insert("actionSource", 251);                              //执行动作源标记  0：自定义动作，251：内部动作，252：外部动作
    taskjson1.insert("actionCode", actionCode);                         //动作命令 4：顶盘举升 3：顶盘下降
    taskjson1.insert("moveFlag", moveFlag);                             //顶盘状态 0：保持 1：降下移动 2：举升移动

    List.insert(0,4);
    List.insert(1,0);
    List.insert(2,0);
    List.insert(3,0);
    List.insert(4,0);
    List.insert(5,0);
    List.insert(6,0);
    List.insert(7,0);

    taskjson1.insert("paraList", List);                                 //动作参数列表

    taskjosnList.append(taskjson1);                                     //任务列表

    taskjson.insert("taskList", taskjosnList);                          //任务列表

    return  taskjson;
}

QJsonObject sapMsgInterface::JsonTaskAgvAction_1(SAPExcelInfo SAPExcelInfoI, int station, int actionCode, QString taskType, int moveFlag, bool flag)
{
    QJsonObject taskjson;
    QJsonObject taskjson1;
    QJsonObject taskjson2;
    QJsonArray taskjosnList;
    QJsonArray List;
    QJsonArray List1;

    taskjson.insert("taskId", SAPExcelInfoI.taskId);                    // 任务 ID
    taskjson.insert("agvId", SAPExcelInfoI.agvNum.toInt());             // AGV编号

    // 顶盘降下前往目标位置
    if(flag)
    {
        taskjson2.insert("unitId", SAPExcelInfoI.taskId_ess + "-Start");// 子任务 ID
        taskjson2.insert("taskType", 3);                                // 任务类型
        taskjson2.insert("station", 0);                                 // 目标站点
        taskjson2.insert("actionSource", 0);                            // 执行动作源标记 0：自定义动作，251：内部动作，252：外部动作
        taskjson2.insert("actionCode", 102);                            // 动作命令 101:顶盘举升 102：顶盘下降
        taskjson2.insert("moveFlag", moveFlag);                         // 顶盘状态 0：保持 1：降下移动 2：举升移动

        taskjosnList.append(taskjson2);                                 // 任务列表
    }

    taskjson1.insert("unitId", SAPExcelInfoI.taskId_ess);               // 子任务 ID
    taskjson1.insert("taskType", 3);                                    // 任务类型
    taskjson1.insert("station", station);                               // 目标站点

    if(taskType == "Action")
    {
        taskjson1.insert("endConfirm", 1);                              // 任务完成后确认，一般用于放行
    }

    taskjson1.insert("actionSource", 0);                                // 执行动作源标记 0：自定义动作，251：内部动作，252：外部动作
    taskjson1.insert("actionCode", actionCode);                         // 动作命令 101:阻挡棒举升 102：阻挡棒下降
    taskjson1.insert("moveFlag", moveFlag);                             // 顶盘状态 0：保持 1：降下移动 2：举升移动

    taskjosnList.append(taskjson1);                                     // 任务列表

    taskjson.insert("taskList", taskjosnList);                          // 任务列表

    return  taskjson;
}

void sapMsgInterface::PostTaskAgvAction(SAPExcelInfo SAPExcelInfoI, int station, int actionCode, QString taskType, int moveFlag, bool flag)
{
    QJsonObject postJson;

    qDebug()<<"PostTaskAgvAction--> taskId:"<<SAPExcelInfoI.taskId<<" taskId_ess:"<<SAPExcelInfoI.taskId_ess
           <<" agvNum:"<<SAPExcelInfoI.agvNum<<" station:"<<station<<" actionCode:"<<actionCode<<" taskType:"<<taskType
             <<" moveFlag:"<<moveFlag<<" flag:"<<flag;

    if(actionCode > 100)
    {
        // 自定义动作
        postJson = JsonTaskAgvAction_1(SAPExcelInfoI, station, actionCode, taskType, moveFlag, flag);
    }
    else if(actionCode < 100)
    {
        // 内部动作
        postJson = JsonTaskAgvAction(SAPExcelInfoI, station, actionCode, taskType, moveFlag, flag);
    }

    setWebService_Post(SAPExcelInfoI.taskId_ess, sapPathMap.value(1012).Path, postJson, "", sapPathMap.value(1012).Type, "");
}

QJsonObject sapMsgInterface::JsonTaskAgvRunAction(SAPExcelInfo SAPExcelInfoI)
{
    QJsonObject taskjson;

    taskjson.insert("taskId", SAPExcelInfoI.taskId);                //任务 ID
    taskjson.insert("unitId", SAPExcelInfoI.taskId_ess);            //子任务 ID
    taskjson.insert("endConfirm", true);                            //结束放行

    return  taskjson;
}

void sapMsgInterface::PostTaskAgvRunAction(SAPExcelInfo SAPExcelInfoI)
{
    qDebug()<<"PostTaskAgvRunAction-->taskId:"<<SAPExcelInfoI.taskId<<" taskId_ess:"<<SAPExcelInfoI.taskId_ess;
    QJsonObject postJson = JsonTaskAgvRunAction(SAPExcelInfoI);
    setWebService_Post(SAPExcelInfoI.taskId_ess, sapPathMap.value(1013).Path, postJson, "", sapPathMap.value(1013).Type, "");
}

QJsonObject sapMsgInterface::JsonTaskAgvCancel(SAPExcelInfo SAPExcelInfoI)
{
    QJsonObject taskjson;

    taskjson.insert("taskId", SAPExcelInfoI.taskId);                //任务 ID
    taskjson.insert("unitId", SAPExcelInfoI.taskId_ess);            //子任务 ID

    return  taskjson;
}

void sapMsgInterface::PostTaskAgvCancel(SAPExcelInfo SAPExcelInfoI)
{
    qDebug()<<"PostTaskAgvCancel-->taskId:"<<SAPExcelInfoI.taskId<<" taskId_ess:"<<SAPExcelInfoI.taskId_ess;
    QJsonObject postJson = JsonTaskAgvCancel(SAPExcelInfoI);
    setWebService_Post(SAPExcelInfoI.taskId_ess, sapPathMap.value(1015).Path, postJson, "", sapPathMap.value(1015).Type, "");
}

void sapMsgInterface::PostTaskAgvMusic(int AgvNum, int MusicNum)
{
    qDebug()<<"PostAgvMusic-->AgvNum:"<<AgvNum;
    QJsonObject postJson;
    postJson.insert("agvId", AgvNum);       // AGV 编号
    postJson.insert("musicId", MusicNum);   // 播放语音编号
    setWebService_Post("", sapPathMap.value(1016).Path, postJson, "", sapPathMap.value(1016).Type, "");
}

void sapMsgInterface::PostTaskAgvClearTraffControlTask(int AgvNum)
{
    qDebug()<<"PostTaskAgvClearTraffControlTask-->AgvNum:"<<AgvNum;

    QJsonObject postJson;

    postJson.insert("agvId", AgvNum);        // AGV 编号 0:清除所有AGV 非0：清除指定AGV
    postJson.insert("ipAddress", 0);         // 主机通信地址

    setWebService_Post("", sapPathMap.value(1017).Path, postJson, "", sapPathMap.value(1017).Type, "");
}

void sapMsgInterface::PostTaskAgvCancelTask(int AgvNum)
{
    qDebug()<<"PostTaskAgvCancelTask-->AgvNum:"<<AgvNum;

    QJsonObject postJson;

    postJson.insert("mDeviceNo", AgvNum);           // AGV 编号
    postJson.insert("mCurrentCommand", 11);         // 任务指令

    setWebService_Post("", sapPathMap.value(1018).Path, postJson, "", sapPathMap.value(1018).Type, "");
}

//Get SAP 数据
void sapMsgInterface::setWebService_Get(QString LabelNo, QString UrlPath,
                                        QString UserBadge, QString Type)
{
    allWebConut++;
    QUrl url(UrlPath);
    QNetworkRequest NetworkRequest;
    NetworkRequest.setUrl(url);
    NetworkRequest.setRawHeader("User",QString("{%1}").arg("User6537").toLatin1());
    NetworkRequest.setRawHeader("Accept-Language","{en-US}");
    QNetworkReply*  NetworkReply = NetworkMgr.get(NetworkRequest);

    for(int i=0;i<WebServiceItiemMap.length();i++){
        if(WebServiceItiemMap[i].ikey==LabelNo){
            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
            WebServiceItiemMap.removeAt(i);i--;
            qDebug()<<"WebServiceItiemMap.removeAt(i) "<<UrlPath;
        }
    }

    WebServiceItiem WebServiceItiem0;
    WebServiceItiem0.ikey=LabelNo;             //唯一键
    WebServiceItiem0.UrlPath=UrlPath;       //路径
    WebServiceItiem0.actionType=Type;       //操作类型  WS02 WS03 …… post
    WebServiceItiem0.userBadge=UserBadge;   //员工工号
    WebServiceItiem0.LabelNo=LabelNo;
    WebServiceItiem0.NetworkRepItiem=NetworkReply;
    WebServiceItiemMap.append(WebServiceItiem0);

    qDebug()<<"ikey:"<<WebServiceItiem0.ikey<<" Send UrlPath: "<<UrlPath;

}

void sapMsgInterface::setWebService_Get_Camera(QString LabelNo, QString UrlPath, QString Type)
{
    allWebConut++;
    QUrl url(UrlPath);
    QNetworkRequest NetworkRequest;
    NetworkRequest.setUrl(url);
    NetworkRequest.setRawHeader("User",QString("{%1}").arg("User6537").toLatin1());
    NetworkRequest.setRawHeader("Accept-Language","{en-US}");
    QNetworkReply*  NetworkReply = NetworkMgr.get(NetworkRequest);

    for(int i=0;i<WebServiceItiemMap.length();i++){
        if(WebServiceItiemMap[i].ikey==LabelNo){
            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
            WebServiceItiemMap.removeAt(i);i--;
            qDebug()<<"WebServiceItiemMap.removeAt(i) "<<UrlPath;
        }
    }

    WebServiceItiem WebServiceItiem0;
    WebServiceItiem0.ikey=LabelNo;             //唯一键
    WebServiceItiem0.UrlPath=UrlPath;       //路径
    WebServiceItiem0.actionType=Type;       //操作类型 Camera
    WebServiceItiem0.LabelNo=LabelNo;
    WebServiceItiem0.NetworkRepItiem=NetworkReply;
    WebServiceItiemMap.append(WebServiceItiem0);

    qDebug()<<"sationId:"<<WebServiceItiem0.sationId<<" Send UrlPath: "<<UrlPath;
}

//post 数据给 SAP
void sapMsgInterface::setWebService_Post(QString iKey,QString UrlPath, QJsonObject postJson,
                                         QString UserBadge, QString Type,QString positionCode)
{
    QUrl url(UrlPath);
    QNetworkRequest NetworkRequest;
    NetworkRequest.setUrl(url);//地址信息

    NetworkRequest.setRawHeader("User",QString("{%1}").arg(UserBadge).toLatin1());
    NetworkRequest.setRawHeader("Accept-Language","{en-US}");//选中语言类型
    NetworkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/json;charset=utf-8");//"text/json" 内容编码类型
    QNetworkReply*NetworkReply=NetworkMgr.post(NetworkRequest,QJsonDocument(postJson).toJson());

    for(int i=0;i<WebServiceItiemMap.length();i++){
        if(WebServiceItiemMap[i].ikey==iKey){
            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
            WebServiceItiemMap.removeAt(i);i--;
        }
    }

    WebServiceItiem WebServiceItiem0;
    WebServiceItiem0.ikey=iKey;                 //唯一键
    WebServiceItiem0.UrlPath=UrlPath;           //路径
    WebServiceItiem0.queryJson=postJson;        //请求数据
    WebServiceItiem0.userBadge=UserBadge;       //员工工号
    WebServiceItiem0.actionType=Type;           //操作类型  WS02 WS03 …… post
    WebServiceItiem0.positionCode=positionCode; //特殊ikey

    WebServiceItiem0.NetworkRepItiem=NetworkReply;
    WebServiceItiemMap.append(WebServiceItiem0);

//    if(Type!="action0"){
//        qDebug()<<"Post-->UrlPath: "<<UrlPath;
//        qDebug()<<"Post-->postJson: "<<postJson;
//    }
    qDebug()<<"Post-->Type: "<<Type;
    qDebug()<<"Post-->UrlPath: "<<UrlPath;
    qDebug()<<"Post-->postJson: "<<postJson;

}


void sapMsgInterface::setWebService_Post_WS06(QString iKey, QString UrlPath, QJsonArray postJson, QString UserBadge, QString Type)
{
    QUrl url(UrlPath);
    QNetworkRequest NetworkRequest;
    NetworkRequest.setUrl(url);//地址信息

    NetworkRequest.setRawHeader("User",QString("{%1}").arg(UserBadge).toLatin1());
    NetworkRequest.setRawHeader("Accept-Language","{en-US}");//选中语言类型
    NetworkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/json;charset=utf-8");//"text/json" 内容编码类型
    QNetworkReply*NetworkReply=NetworkMgr.post(NetworkRequest,QJsonDocument(postJson).toJson());

    for(int i=0;i<WebServiceItiemMap.length();i++){
        if(WebServiceItiemMap[i].ikey==iKey){
            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
            WebServiceItiemMap.removeAt(i);i--;
        }
    }

    WebServiceItiem WebServiceItiem0;
    WebServiceItiem0.ikey=iKey;             //唯一键
    WebServiceItiem0.UrlPath=UrlPath;       //路径
    WebServiceItiem0.actionType=Type;       //操作类型  WS02 WS03 …… post
    WebServiceItiem0.userBadge=UserBadge;   //员工工号
    WebServiceItiem0.postArray=postJson;    //请求数据
    WebServiceItiem0.NetworkRepItiem=NetworkReply;
    WebServiceItiemMap.append(WebServiceItiem0);

    if(Type!="action0" && Type!="action22"){
        qDebug()<<"Post-WS06->UrlPath: "<<UrlPath;
        qDebug()<<"Post-WS06->postJson: "<<postJson;
    }

}

void sapMsgInterface::setWebService_SAOP_Post(QString iKey, QString UrlPath, QDomDocument doc, QString UserBadge, QString Type)
{
    QUrl url(UrlPath);
    QNetworkRequest NetworkRequest;
    NetworkRequest.setUrl(url);//地址信息

    NetworkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"text/xml;charset=utf-8");//"text/json" 内容编码类型
    NetworkRequest.setRawHeader("SOAPAction", "http://tempuri.org/IJDSWS/PrintLabel");
    QNetworkReply*NetworkReply=NetworkMgr.post(NetworkRequest,doc.toString().toUtf8().constData());

    for(int i=0;i<WebServiceItiemMap.length();i++){
        if(WebServiceItiemMap[i].ikey==iKey){
            WebServiceItiemMap[i].NetworkRepItiem->deleteLater();//关闭
            WebServiceItiemMap.removeAt(i);i--;
        }
    }

    WebServiceItiem WebServiceItiem0;
    WebServiceItiem0.ikey=iKey;             //唯一键
    WebServiceItiem0.UrlPath=UrlPath;       //路径
    WebServiceItiem0.actionType=Type;       //操作类型  WS02 WS03 …… post
    WebServiceItiem0.userBadge=UserBadge;   //员工工号
    WebServiceItiem0.doc=doc;    //请求数据
    WebServiceItiem0.NetworkRepItiem=NetworkReply;
    WebServiceItiemMap.append(WebServiceItiem0);

    if(Type!="action0" && Type!="action22"){
        qDebug()<<"--SAOP-->UrlPath: "<<UrlPath;
        qDebug()<<"--SAOP-->DOC: "<<doc.toString().toUtf8().constData();
    }

}
